package org.springblade.common.mvc.conf;

import org.springblade.common.cache.DictCache;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.ResultCode;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.WebUtil;
import org.springblade.modules.system.entity.Dict;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Date 10:24 2024/11/04
 * @Description {
 *   自定义请求拦截器
 * }
 * @Author lsay
 **/
public class MyInterceptor implements HandlerInterceptor {

	@Autowired
	private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		String ua = request.getHeader(WebUtil.USER_AGENT_HEADER);
		if(Func.isNotEmpty(ua) && ua.contains("MicroMessenger")){
			User user = userService.getById(AuthUtil.getUserId());
			if(Func.isNotEmpty(user) && Func.isNotEmpty(user.getPhone())){
				List<Dict> dictList = DictCache.getList("phone_limit_login");
				if(Func.isNotEmpty(dictList)){
					long count = dictList.stream().filter(e -> e.getDictKey().equals(user.getPhone())).count();
					if(count > 0){
						throw new ServiceException(ResultCode.UN_AUTHORIZED);
					}
				}
			}
		}
        return true;
    }

}
